from sqlalchemy.orm import Session
from app.models.case import Case
from app.schemas.case import CaseCreate, CaseUpdate
from typing import List, Optional
from app.ai.ai_service import ai_service

# 获取案例通过ID
def get_case(db: Session, case_id: int):
    return db.query(Case).filter(Case.id == case_id).first()

# 获取案例列表
def get_cases(db: Session, skip: int = 0, limit: int = 100, category: Optional[str] = None, approved: Optional[bool] = None, search: Optional[str] = None):
    query = db.query(Case)
    if category:
        query = query.filter(Case.category == category)
    if approved is not None:
        query = query.filter(Case.approved == approved)
    if search:
        query = query.filter(
            Case.title.contains(search) | 
            Case.description.contains(search) | 
            Case.keywords.contains(search)
        )
    return query.offset(skip).limit(limit).all()

# 创建案例
def create_case(db: Session, case: CaseCreate, created_by: int):
    db_case = Case(
        title=case.title,
        description=case.description,
        solution=case.solution,
        category=case.category,
        keywords=case.keywords,
        created_by=created_by,
        approved=case.approved if case.approved is not None else False
    )
    db.add(db_case)
    db.commit()
    db.refresh(db_case)
    return db_case

# 更新案例
def update_case(db: Session, case_id: int, case: CaseUpdate):
    db_case = db.query(Case).filter(Case.id == case_id).first()
    if db_case:
        if case.title is not None:
            db_case.title = case.title
        if case.description is not None:
            db_case.description = case.description
        if case.solution is not None:
            db_case.solution = case.solution
        if case.keywords is not None:
            db_case.keywords = case.keywords
        if case.category is not None:
            db_case.category = case.category
        if case.approved is not None:
            db_case.approved = case.approved
        db.commit()
        db.refresh(db_case)
    return db_case

# 删除案例
def delete_case(db: Session, case_id: int):
    db_case = db.query(Case).filter(Case.id == case_id).first()
    if db_case:
        db.delete(db_case)
        db.commit()
    return db_case

# 搜索相似案例 - 使用AI模块进行更精确的匹配
def search_similar_cases(db: Session, query: str, category: Optional[str] = None, limit: int = 10):
    """
    使用AI模块搜索相似案例
    
    Args:
        db: 数据库会话
        query: 查询文本
        category: 案例分类（可选）
        limit: 返回结果数量限制
        
    Returns:
        相似案例列表，每个元素为(案例, 相似度)的元组
    """
    if not query:
        return []
    
    # 使用AI服务进行相似案例匹配
    try:
        similar_cases = ai_service.match_similar_cases(query, db, category=category, limit=limit)
        return similar_cases
    except Exception as e:
        # 如果AI匹配失败，回退到原有的简单匹配方法
        print(f"AI匹配失败，使用简单匹配方法: {e}")
        return search_similar_cases_simple(db, query, category, limit)

def search_similar_cases_simple(db: Session, query: str, category: Optional[str] = None, limit: int = 10):
    """
    简单的关键词匹配实现（作为备选方案）
    """
    search_terms = query.split()
    query_obj = db.query(Case)
    
    if category:
        query_obj = query_obj.filter(Case.category == category)
    
    # 计算匹配度（简化实现）
    matches = []
    for case in query_obj.all():
        score = 0
        case_text = f"{case.title} {case.description} {case.keywords or ''}".lower()
        for term in search_terms:
            if term.lower() in case_text:
                score += 1
        if score > 0:
            matches.append((case, score / len(search_terms)))
    
    # 按匹配度排序
    matches.sort(key=lambda x: x[1], reverse=True)
    return [(case, score) for case, score in matches[:limit]]